window.View = function()
{
    // 获取接口路径
    this.Paths = null;
    // 获取所有选中元素
    this.Elems = null;
    // 视图模板
    this.Tmps = null;

    this.request = null;

    this.chartBtn = null;
};

View.prototype = {

    /** 初始化视图*/
    init: function (o) {
        // 获取接口路径
        this.Paths = o.paths;
        // 获取所有选中元素
        this.Elems = this.H.getElementsByIds(o.ids);

        this._getTopLoadElement();

        // 获取所有视图模板
        this.Tmps = this.H.getTemplatesModle(o.templates);

        this.charts = this.echarts.init(this.Elems["chartsContainer"]);

        // 初始化select2
        var self = this;

        var oCascadeData = new self.CascadeData();

        oCascadeData.init(this.Paths["getrelationPath"]);

        $("select.ad-js-select").select2({
            //placeholder: "请选择查询条件",
            allowClear: true
        }).on("change", function (e) {

            self.beforeSend();

            var result = self.Control.select2ChangeHandle(e, self.Elems["allsearchform"].children, self);

            oCascadeData.askdata(result, function (data) {
                for (var attr in data) {
                    var oselect = document.getElementById("select_" + attr.toUpperCase());

                    if (!oselect) continue;

                    var ofrag = document.createDocumentFragment();

                    for (var i = 0, item; item = data[ attr ][ i ]; i += 1) {
                        var newOption = document.createElement("option");

                        newOption.value = item.id;

                        newOption.innerHTML = item.name;

                        ofrag.appendChild(newOption);
                    }

                    oselect.innerHTML = "";

                    oselect.appendChild(ofrag);

                    self.$(oselect).select2("val", tv);
                }

                self.afterSend();
            });
        });

        $('input.ad-js-timer').glDatePicker({
            showAlways: false,
            format: 'yyyy-mm-dd',
            nextArrow: ">",
            prevArrow: "<",
            dowNames: [ "日", "一", "二", "三", "四", "五", "六" ],
            monthNames: [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ]
        });

        this.initCreateTable();

        this.initCondtion();

        this.bindEvent();

        var oRel = new this.Relational();

        oRel.init(this.Elems["RelationalPath"].value || null, this.Control.getWhereItem, this.Control.getItem, this.Control);
    },

    initCreateTable: function () {
        var self = this;

        var itemStr = self.Elems["dataContainer"].value;

        if (itemStr) {
            var oItem = JSON.parse(decodeURIComponent(itemStr));

            this.Control.setItem(oItem);

            this.createTable();

            this.afterSend();
        }
        else {
            alert("无数据")
        }
    },

    initCondtion: function () {

        var self = this;

        $("#ad-js-condList").children().each(function(){

            if( $(this).hasClass("ad-doc-condFrist") ){ return ;}

            var oDd = $(this);

            var dataName = oDd.attr("data-name");

            var type = oDd.attr("data-status");

            var oLabel = oDd.find("label").text();

            var oA = oDd.find("div a.active");

            var showString = "";
            var obj = [];
            oA.each(function(){
                var dataValue = $(this).attr("data-value");
                var name = $(this).html();
                if( !dataValue ){ return false;}
                obj.push( dataValue );
                showString+=name+"，";
            });

            if( obj.length ==0 ) return ;

            showString = showString.substring(0,showString.length-1);

            var oo = {"id":"con_"+dataName,"title":oLabel,"type": type , "value":showString};

            self.initPaint( oo , obj , dataName , oLabel, type );

        });

        $("#ad-js-condList2").children().each(function(){


            if($(this).hasClass("ad-btn-selector")){

            }else{

                var templateConditonData = {};

                var conditionData = [ "", ""];

                var inputs = this.parentNode.getElementsByTagName("input");

                var _parent =  $(this)[0];

                var sName = _parent.getAttribute("data-name");

                var sTitle = _parent.getAttribute("data-title");

                var sUon = this.parentNode.getElementsByTagName("b")[0].innerHTML;

                sUon = sUon == "-" ? "" : sUon;

                var sMin = inputs[ 0 ].value;

                var sMax = inputs[ 1 ].value;

                var condRange = self.Control.getCondRange( this, sMin, sMax, sUon );

                if( condRange.string ) templateConditonData["value"] = condRange.string;

                if( condRange.min || condRange.max ) conditionData = [ condRange.min, condRange.max ];

                self.initPaint( templateConditonData, conditionData, sName, sTitle, 1  );

            }

        });

        $(function(){
            self.$("#ad-js-closeCond").click();
        })

    },

    createTable: function () {
        var self = this;

        var data = self.Control.getItem();

        if (!this.$.isEmptyObject(data) && !this.$.isEmptyObject(data["d"]) && data["d"]["r"]["i"].length) {
            var oSortTool = new SortTool();

            var JSONDATA = data;

            new this.DataGrid({
                target: this.Elems["tableResponsive"],
                item: JSONDATA["d"],
                headThClick: function () {
                    var filed = this.className.substring(2);

                    oSortTool.setItem(JSONDATA);

                    var result = oSortTool.sortDescItem(filed) || null;

                    if (result) {
                        this.currentObj.reInitialize({
                            item: result["d"]
                        });

                        var tag = this.className.split(" ")[ 0 ].substring(2);

                        self.$(document.getElementsByClassName("grid_groud")).removeClass("grid_groud");

                        self.$(document.getElementsByClassName("b_" + tag)).addClass("grid_groud");

                        self.$("th.h_" + tag, this.currentObj._target).addClass("grid_groud").siblings().removeClass("grid_groud");

                        self.Elems["colorLevels"]._st = 0;

                        self.Elems["colorLevels"].innerHTML = '<i class="fa fa-fire"></i> 打开色阶';

                    }
                }
            });
        }
        else {
            var element = this.Control.printDataToMapPanel([
                []
            ], this.Tmps["nullData"]);

            this.$(this.Elems["tableResponsive"]).html(element);
        }

    },

    _getTopLoadElement: function () {
        try {
            this.Elems["loading"] = top.window.FRAMES["container"].window.document.getElementById("ad-js-loading") || this.Elems["loading"];
        }
        catch (e) {
        }
        ;
    },

    _paneBindEvent: function () {
        var self = this;


        document.body.onload = function(){
           Handle&&Handle.loadingHide();
        };

        self.Elems["closePage"].onclick = function () {
            var ofdetails = top.window.FRAMES[ "details" ].element;

            ofdetails.style.opacity = 0;

            ofdetails.style.zIndex = -1;

            ofdetails.src = "";

            ofdetails.onload = null;
        }

        var oTableColorLevelRender = new self.TableColorLevelRender();


        self.Elems["colorLevels"].onclick = function () {
            var originTd = self.Elems["tableResponsive"].getElementsByTagName("td"),

                $elem = self.$(self.Elems["tableResponsive"].getElementsByTagName("td"));

            //console.log( self.Elems["tableResponsive"].getElementsByTagName("td").length );

            if (!$elem[ 0 ]) {
                self.toastr.warning("无数据，无法生成色阶");

                return false;
            }

            oTableColorLevelRender.setItem(originTd);

            if (!self.Elems["tableResponsive"].children[ 0 ].children[ 0 ].getAttribute("data-level")) {
                self.toastr.warning("当前模型不支持色阶功能");
                return false;
            }

            if (this._st) {
                oTableColorLevelRender.clearLevels();

                this._st = 0;

                this.innerHTML = '<i class="fa fa-fire"></i> 打开色阶';
            }
            else {
                //console.log( oTableColorLevelRender.originElements )

                oTableColorLevelRender.getSelfArray(oTableColorLevelRender.originElements);

                //return false;

                var result = oTableColorLevelRender.selfSort(oTableColorLevelRender.selfArray) || [];

                oTableColorLevelRender.setRender(result);

                this._st = 1;

                this.innerHTML = '<i class="fa fa-fire"></i> 关闭色阶';
            }

            $elem = null;

            oTableColorLevelRender.selfArray = [];
        }

    },

    _dwhereSubmit: function () {
        var self = this;

//        self.Elems["search"].onclick = function () {
//            self.Elems["sreachwrap"].style.top = 0;
//        }

//        self.Elems["closeallsearchwrap"].onclick = function () {
//            self.Elems["sreachwrap"].style.top = "-500px";
//        }
//
//        self.Elems["resetallsearchwrap"].onclick = function () {
//            self.$(self.Elems["allsearchform"].getElementsByTagName("select")).select2("val", "");
//
//            self.$("input:not(:hidden)", self.Elems["allsearchform"]).val("");
//
//            self.Elems["submitallsearchwrap"].onclick();
//        }

        self.$(self.Elems["condwrapper"]).delegate("li", "click", function () {
            if (!confirm("是否撤销此条件项？")) return false;

            var group = self.$("div[data-name='" + this.children[ 0 ].id.substring(2) + "']", self.Elems["allsearchform"])[ 0 ];

            var oselect = group.getElementsByTagName("select");

            if (oselect[ 0 ]) {
                self.$(oselect).select2("val", "");
            }
            else {
                var inputs = group.getElementsByTagName("input");

                inputs[ 0 ].value = inputs[ 1 ].value = "";
            }

//            self.Elems["submitallsearchwrap"].onclick();

            this.parentNode && this.parentNode.removeChild(this);
        })

        self.$("a", self.Elems["saveConditioncontainer"]).click(function () {

            return false;
            var value = this.getAttribute("data-cond");

            if (value) {
                var JSONCONDS = JSON.parse(value);

                var formGroup = self.Elems["allsearchform"].children;

                for (var i = 0, f; f = formGroup[ i ]; i += 1) {
                    if (f.type == "hidden") continue;

                    var selects = f.getElementsByTagName("select")[ 0 ];

                    var sName = f.getAttribute("data-name");

                    var whereData = JSONCONDS[ sName ];

                    if (selects) {
                        $(selects).select2("val", whereData);
                    }
                    else {
                        var inputs = f.getElementsByTagName("input");

                        inputs[ 0 ].value = whereData[ 0 ];

                        inputs[ 1 ].value = whereData[ 1 ];
                    }
                }

//                self.Elems["submitallsearchwrap"].onclick();
            }
        });

    },

    _setCharts: function () {
        var self = this;

        var chartsList = self.Elems["chartsList"];

        var oCanvasDown = new self.CanvasDown();

        chartsList && self.$("a", chartsList).bind("click", function () {
            self.beforeSend();

            var container = self.Elems["chartsContainer"];

            container.style.zIndex = 4;

            container._btn = this;

            var chart = new ChartsControl(self.charts);

            chart.init(this.getAttribute("data-tag"), self.Control.getItem(), {
                error: function (infoData) {
                    self.toastr.warning(infoData);
                }
            });

            self.afterSend();

            self.$(this.parentNode.parentNode.parentNode).addClass("active").prev().removeClass("active");

            self.Elems["downCharts"].style.display = "inline-block";

            self.Elems["colorLevels"].style.display = "none";

            self.chartBtn = this;
        });

        self.Elems["downCharts"].onclick = function () {
            oCanvasDown.saveImageInfo(self.Elems["chartsContainer"], this);
        }

        self.Elems["tableShow"].onclick = function () {
            self.Elems["chartsContainer"].style.zIndex = -1;

            self.Elems["downCharts"].style.display = "none";

            self.Elems["colorLevels"].style.display = "inline-block";

            self.Elems["chartsContainer"]._btn = null;

            self.$(this.parentNode).addClass("active").next().removeClass("active");

            self.chartBtn = null;
        }
    },

    bindEvent: function () {
        this._paneBindEvent();

        this._dwhereSubmit();

        this._setCharts();

        this._modalLayer();

        this._linkToXCase();

        this.condLayerHandle();
    },

    _modalLayer: function () {
        var self = this;

        self.$(self.Elems["searchModal1"]).on('show.bs.modal', function (e) {
            self.Elems["searchModaltextarea"].value = "";

            var DATA = [];

            var oselect = e.relatedTarget.parentNode.getElementsByTagName("select");

            for (var i = 0, elem = oselect[ 0 ].children, f; f = elem[ i ]; i += 1) {
                DATA.push({ title: f.innerHTML, value: f.value });
            }

            self.Elems["searchModalbtn"]._value = DATA;

            self.Elems["searchModalbtn"]._select = oselect;

        })

        self.Elems["searchModalbtn"].onclick = function () {
            if (this._value) {
                var newArray = [];

                var strs = self.Elems["searchModaltextarea"].value.split("，");

                for (var p = 0, pf; pf = strs[ p ]; p += 1) {
                    for (var i = 0, f; f = this._value[ i ]; i += 1) {
                        if (f.title.indexOf(pf) != -1) {
                            newArray.push(f.value);
                        }
                    }
                }

                self.$(this._select).select2("val", newArray).change();

                self.$(self.Elems["searchModal1"]).modal("hide");
            }
        }

        self.$(self.Elems["searchModal2"]).on('show.bs.modal', function (e) {
            var oselect = e.relatedTarget.parentNode.getElementsByTagName("select");

            self.Elems["searchModalSubmit"]._select = oselect;

            if (oselect[ 0 ]) {
                var DATA = [];

                var checked = self.$(oselect).select2('val');

                for (var i = 0, elem = oselect[ 0 ].children, f; f = elem[ i ]; i += 1) {
                    DATA.push({ title: f.innerHTML, value: f.value, checked: checked.indexOf(f.value) == -1 ? "" : "checked"  });
                }

                var element = self.Control.printDataToMapPanel(DATA, self.Tmps["checkboxLayer"]);

                self.$(self.Elems["searchModal2content"]).html(element);
            }
        })

        self.Elems["searchModalCheckAll"].onclick = function () {
            var checks = self.Elems["searchModal2content"].getElementsByTagName("input");

            for (var i = 0, f; f = checks[ i ]; i += 1) {
                f.checked = true;
            }
        }

        self.Elems["searchModalReCheck"].onclick = function () {
            var checks = self.Elems["searchModal2content"].getElementsByTagName("input");

            for (var i = 0, f; f = checks[ i ]; i += 1) {
                f.checked = f.checked ? false : true;
            }
        }

        self.Elems["searchModalSubmit"].onclick = function () {
            var checks = self.Elems["searchModal2content"].getElementsByTagName("input");

            var value = [];

            for (var i = 0, f; f = checks[ i ]; i += 1) {
                if (f.checked) {
                    value.push(f.value);
                }
            }

            self.$(this._select).select2("val", value).change();

            self.$(self.Elems["searchModal2"]).modal("hide");
        }
    },

    /** 请求前处理*/
    beforeSend: function () {
        var oloading = this.Elems["loading"];

        oloading.style.display = "block";
        oloading.style.opacity = 1;
        oloading.style["-webkit-transition"] =
            oloading.style["-moz-transition"] =
                oloading.style["-o-transition"] =
                    oloading.style["transition"] = "opacity 0.35s ease";
    },

    afterSend: function () {
        var oloading = this.Elems["loading"];
        oloading.style.opacity = 0;
        oloading.style.display = "none";
    },

    searchDatalSuccess: function (data, o, callback) {
        var self = this;

        if (data) {
            self.Elems["colorLevels"]._st = 0;

            self.Elems["colorLevels"].innerHTML = '<i class="fa fa-fire"></i> 打开色阶';

            this.Control.setItem(data);

            if (!this.$.isEmptyObject(data) && !this.$.isEmptyObject(data["d"]) && data["d"]["r"]["i"].length) {
                var oSortTool = new SortTool();

                var JSONDATA = this.Control.getItem();

                new this.DataGrid({
                    target: this.Elems["tableResponsive"],
                    item: JSONDATA["d"],
                    headThClick: function () {
                        var filed = this.className.substring(2);

                        oSortTool.setItem(JSONDATA);

                        var result = oSortTool.sortDescItem(filed) || null;

                        if (result) {
                            this.currentObj.reInitialize({
                                item: result["d"]
                            });

                            var tag = this.className.split(" ")[ 0 ].substring(2);

                            self.$(document.getElementsByClassName("grid_groud")).removeClass("grid_groud");

                            self.$(document.getElementsByClassName("b_" + tag)).addClass("grid_groud");

                            self.$("th.h_" + tag, this.currentObj._target).addClass("grid_groud").siblings().removeClass("grid_groud");

                            self.Elems["colorLevels"]._st = 0;

                            self.Elems["colorLevels"].innerHTML = '<i class="fa fa-fire"></i> 打开色阶';
                        }
                    }
                });
            }
            else {
                var element = this.Control.printDataToMapPanel([
                    []
                ], this.Tmps["nullData"]);

                this.$(this.Elems["tableResponsive"]).html(element);
            }
        }

        this.afterSend();

        typeof callback == "function" && callback.call(this);

    },

    searchData: function (data, callback) {
        var callbackObject = {
            context: this,
            success: this.searchDatalSuccess || function () {
            },
            beforeSend: this.beforeSend || function () {
            },
            callback: callback || function () {
            }
        };

        this.Control.post(this.Paths["getSearchData"], data, callbackObject, "json")
    },
    _linkToXCase: function () {
        this.H.jumpProject();
    },
    condLayerHandle : function()
    {
        var self = this;

        self.Elems["search"].onclick = function ( ev ) {
            var event = ev||window.event;
            self.Elems["sreachwrap"].style["-webkit-transition"] =
                self.Elems["sreachwrap"].style["-ms-transition"] =
                    self.Elems["sreachwrap"].style["-ms-transition"] =
                        self.Elems["sreachwrap"].style["-o-transition"] =
                            self.Elems["sreachwrap"].style["transition"] = "top .3s ease";
            self.Elems["sreachwrap"].style.top = 0;


            if( event.stopPropagation ){ event.stopPropagation(); } else { event.cancelBubble  = true; }
        };
        //设置默认高度
//        self.$("#ad-js-condLayer").attr("data-height",self.$("#ad-js-condLayer").height());

        self.$("#ad-js-showTj").on("click",function(){
            self.$("#ad-js-closeCond").click();
        });

        //阻止默认事件
        self.Elems["sreachwrap"].onclick = function( ev ){
            //模拟点击
            var event = ev||window.event;
            if( event.stopPropagation ){ event.stopPropagation(); } else { event.cancelBubble  = true; }
        };

        //绑定window事件 getFrame 用不了
        ( function(){
            var thisWindow = window.documentElement||window.body;
            self.$( top.window ).on("click" , function(){
                self.$("#ad-js-closeCond",thisWindow).click();
            });
            self.$( window ).on("click" , function(){
                self.$("#ad-js-closeCond").click();
            });
            self.$( parent.window ).on("click" , function(){
                self.$("#ad-js-closeCond",thisWindow).click();
            });

            self.$( ".gldp-default" ).on("click" , function( ev ){
                 ev.stopPropagation();
            });

        })();


        // 收起筛选条件
        self.Elems["closeCond"].onclick = function( ev )
        {
            var event = ev||window.event;
            self.Elems["sreachwrap"].style.top = ( -self.Elems["condLayer"].offsetHeight - 20 ) + "px";
            self.Elems["sreachwrap"].style["-webkit-transition"] =
                self.Elems["sreachwrap"].style["-ms-transition"] =
                    self.Elems["sreachwrap"].style["-ms-transition"] =
                        self.Elems["sreachwrap"].style["-o-transition"] =
                            self.Elems["sreachwrap"].style["transition"] = "none";

            self.$( self.Elems["condtionList4"].children[ 0 ] ).siblings().remove();

            var clone = self.Elems["condtionList"].getElementsByTagName("dd");

            self.Elems["condtionList4"].innerHTML = "";

            self.$( clone ).clone().appendTo( self.Elems["condtionList4"] );

            if( event.stopPropagation ){ event.stopPropagation(); } else { event.cancelBubble  = true; }

//            if( clone[ 0 ] )
//            {
//                var oDt = document.createElement("dt");
//
//                oDt.innerHTML = "<i class='fa fa-paint-brush'></i> 清除所有";
//
//                oDt.onclick = function()
//                {
//                    if( !confirm("系统提示：是否删除所有条件？") ) return false;
//
//                    self.Elems["resetConditionSearch"].onclick();
//
//                    self.Elems["conditionSearch"].onclick();
//
////                    self.Elems["condtionList4"].innerHTML = "";
//                }
//
//                self.Elems["condtionList4"].appendChild( oDt );
//            }
        };

        // 筛选条件提交
        self.Elems["conditionSearch"].onclick = function()
        {
            self.Elems["closeCond"].onclick();

            self.search();
        };

        // 重置筛选条件提交
        self.Elems["resetConditionSearch"].onclick = function()
        {
            // 重置数据
            self.Control.resetConditionItem();
            // 重置快捷菜单
            var condListElem = self.$( "li", self.Elems["condList"] );
            // 重置快捷菜单2 - 多选
            var condList2Elem = self.$( "input:checkbox", self.Elems["condList2"] );
            // 重置快捷菜单2 - 范围
            var condList3Elem = self.$( "input:text", self.Elems["condList2"] );

            condListElem.each( function()
            {
                var oA = this.getElementsByTagName("a")[ 0 ];

                if( oA )
                {
                    self.$( oA ).addClass("active").siblings().removeClass("active");

                    self.$( oA ).siblings("span").hide().find("input").val();
                }
            });

            condList2Elem.each( function()
            {
                this.checked = false;
            });

            condList3Elem.val("");

            self.$( self.Elems["condtionList"].getElementsByTagName("dd") ).remove();

            self.Elems["condtionNull"].style.display = "block";

            self.searchHandle();

        };

        self.$("input.ad-js-selectsearch", self.Elems["condLayer"] ).keyup( { self : this }, function( e )
        {
            var self = e.data.self;

            var _$ = self.$;

            var _this = this;

            this._ulItem = this._ulItem ||  _$( this.parentNode ).next().children();

            clearTimeout( self.localSearchTime );

            self.localSearchTime = setTimeout( function()
            {
                _this._ulItem.each( function()
                {
                    var sName = this.getElementsByTagName("input")[ 0 ].getAttribute("data-name");

                    var reg = new RegExp( _this.value, "img" );

                    if( !reg.test( sName ) )
                    {
                        this.style.display = "none";

                    }
                    else
                    {
                        this.style.display = "block";
                    }
                });

            }, 200 );
        });

        self.$("button.ad-js-selectsearchBtn", self.Elems["condLayer"] ).click( { self : this }, function( e )
        {
            var self = e.data.self;

            var _$ = self.$;

            this._ulItem = this._ulItem ||  _$( this.parentNode ).next().children();

            this._text = this._text ||  _$( this ).prev();

            this._ulItem.show();

            this._text.val("")
        });




        // 条件多选浮层
        self.$("div.ad-btn-selector", self.Elems["condLayer"] ).mouseover( function()
        {
            var className = "";
            var oWrap = self.Elems["sreachwrap"];
            var iHeight = oWrap.offsetHeight;
            var iWidth = oWrap.offsetWidth;
            var offset = self.$( this ).offset();
            var iTop = offset.top;
            var iLeft = offset.left;

            this._layer = this._layer || this.children[ 1 ];
            this._height = this._height || this._layer.offsetHeight;
            this._width = this._width || this._layer.offsetWidth;


//            if( ( iTop + this._height ) > iHeight )
//            {
//                if(this._height > iTop) (self.$(  this._layer ).offset({ top:0 }));
//                className += "top";
//            }
//            else
//            {
//
//                className += "bottom";
//            }

            className += "bottom";

            if( ( iLeft + this._width ) > iWidth )
            {

                if(this._width > iLeft)(self.$(  this._layer ).offset({ left:0 }));
                className += " right";
            }
            else
            {
                className += " left";
            }

            this._layer.className = className;

        });

        // 条件菜单，展开 收起
        self.initCondition();

        self.reConditionConut();

        self.$( window ).resize( function()
        {
            self.reConditionConut();
        });

        self.$( self.Elems["condtionList4"] ).delegate("dd", "click", function()
        {

            var sId = this.getElementsByTagName("a")[0].id;

            var ID = sId.substring( 4 );

            $(this).remove();

            $( ".ad-doc-condList #"+sId ).parent().click();
            
            self.search();

//            if( self.Control.removeConditionItem( sId ) )
//            {
//                if( this.parentNode.children.length <= 3  )
//                {
//                    self.$( "dt:last", this.parentNode ).remove();
//                }
//
//                this.parentNode.removeChild( this );
//
//                self.searchHandle();
//            }

        });

        // 多选 反选
        self.$( self.Elems["condList2"] ).delegate("div.ad-btn-selector button", "click", function()
        {
            var isCheckedAll = self.$( this ).hasClass("ad-js-checkedAll");

            var isReChecked = self.$( this ).hasClass("ad-js-reChecked");

            if( !( isCheckedAll || isReChecked ) ) return false;

            var templateConditonData = {};

            var conditionData = [];

            this._parent = this._parent || this.parentNode.parentNode;

            var sName = this._parent.getAttribute("data-name");

            var sTitle = this._parent.getAttribute("data-title");

            var checkedInput = self.$("input:checkbox", this._parent );

            if( isCheckedAll )
            {
                for( var i = 0, f; f = checkedInput[ i ]; i += 1 )
                {
                    if(f.parentNode.parentNode.style.display=="none"){ continue;}

                    f.checked = true;

                    var aValue = f.getAttribute("data-value");

                    var aName = f.getAttribute("data-name");

                    templateConditonData["value"] = templateConditonData["value"] || [];

                    templateConditonData["value"].push( aName );

                    conditionData.push( aValue || "" );
                }
            }
            else if( isReChecked )
            {
                for( var i = 0, f; f = checkedInput[ i ]; i += 1 )
                {
                    if(f.parentNode.parentNode.style.display=="none"){ continue;}

                    if( f.checked )
                    {
                        f.checked = false;
                    }
                    else
                    {
                        f.checked = true;

                        var aValue = f.getAttribute("data-value");

                        templateConditonData["value"] = templateConditonData["value"] || [];

                        templateConditonData["value"].push( aValue );

                        conditionData.push( aValue || "" );
                    }
                }
            }

            templateConditonData["value"] = templateConditonData["value"] ? templateConditonData["value"].join("，") : "";

            self.setCondData( templateConditonData, conditionData, sName, sTitle, 2 );
        });

        // 删除已选条件项
        self.$( self.Elems["condList"] ).delegate("dd", "click", function()
        {
            var sId = this.getElementsByTagName("a")[0].id;

            var ID = sId.substring( 4 );

            if( self.Control.removeConditionItem( sId ) )
            {
                if( this.parentNode.children.length <= 2  )
                {
                    self.Elems["condtionNull"].style.display = "block";
                }
                else
                {
                    self.Elems["condtionNull"].style.display = "none";
                }

                this.parentNode.removeChild( this );

                // 重置快捷菜单
                var condListElem = self.$( "li[data-name='" + ID + "'] a:eq(0)", self.Elems["condList"] );
                // 重置快捷菜单2 - 多选
                var condList2Elem = self.$( "input[name='" + ID + "']", self.Elems["condList2"] );
                // 重置快捷菜单2 - 范围
                var condList3Elem = self.$( "div[data-name='" + ID + "'] input:text", self.Elems["condList2"] );

                if( condListElem[ 0 ] )
                {
                    condListElem.addClass("active").siblings().removeClass("active");

                    self.$( condListElem ).siblings("span").hide().find("input").val();
                }
                else if( condList2Elem[ 0 ] )
                {
                    condList2Elem.each( function()
                    {
                        this.checked = false;
                    });
                }
                else if( condList3Elem[ 0 ] && condList3Elem[ 1 ] )
                {
                    condList3Elem.val("");
                }
                self.searchHandle( ID , null );
            };

        })

        // 快捷条件选择
        self.$( self.Elems["condList"] ).delegate( "a", "click", function()
        {

            if( this.parentNode.tagName == "DD" ) return;

            this._parent = this._parent || this.parentNode.parentNode;

            var conRoot = $( this._parent );

            var isDisable = conRoot.hasClass("disabled");

            if( isDisable ) return false;

            var status = this._parent.getAttribute("data-status");

            var sName = this._parent.getAttribute("data-name");

            var sValue = this.getAttribute("data-value");

            var sTitle = this._parent.getElementsByTagName("label")[0].innerHTML;

            var templateConditonData = {};

            var conditionData = [];
            // 单选
            if( status == 1 )
            {
                conditionData = ["",""];

                self.$( this ).addClass("active").siblings().removeClass("active");

                this._custom = this._custom || this.parentNode.getElementsByTagName("span")[ 0 ];

                if( this._custom && this._custom.style.display == "block" )
                {
                    this._custom.style.display = "none";
                }

                // 自定义区间
                if( sValue == "custom")
                {
                    this._custom = this._custom || this.parentNode.getElementsByTagName("span")[ 0 ];

                    this._custom.style.display = "block";

                    self.$( this._custom.getElementsByTagName("input")).val("");
                }

                var select = self.$( "a.active", this._parent );

                if( sValue && sValue !== "custom"  )
                {
                    templateConditonData["value"] = select[ 0 ].innerHTML;

                    conditionData = sValue.split("|");
                }

                self.setCondData( templateConditonData, conditionData, sName, sTitle, 1  );

            }
            // 多选
            else if( status == 2 )
            {
                this._frist = this._frist || this.parentNode.children[ 0 ];

                if( this == this._frist )
                {
                    self.$( this ).addClass("active").siblings().removeClass("active");
                }
                else
                {
                    self.$( this._frist ).removeClass("active");

                    if( self.$( this ).hasClass("active") )
                    {
                        self.$( this ).removeClass("active");

                        if( !self.$( "a.active", this._parent ).length )
                        {
                            self.$( this._frist ).addClass("active");
                        }
                    }
                    else
                    {
                        self.$( this ).addClass("active");
                    }
                }

                // 搜集多选
                var mselect = self.$( "a.active", this._parent );

                for( var i = 0, mf; mf = mselect[ i ]; i += 1 )
                {
                    var aValue = mf.getAttribute("data-value");

                    if( aValue )
                    {
                        conditionData.push( aValue || "" );

                        templateConditonData["value"] = templateConditonData["value"] || [];

                        templateConditonData["value"].push( mf.innerHTML );
                    }
                }

                templateConditonData["value"] = templateConditonData["value"] ? templateConditonData["value"].join("，") : "";

                self.setCondData( templateConditonData, conditionData, sName, sTitle, 2  );


            }

        }).delegate("button", "click", function()
        {
            if( !self.$( this ).hasClass("btn-info") ) return false;

            var templateConditonData = {};

            var conditionData = [ "", "" ];

            this._parent = this._parent || this.parentNode.parentNode.parentNode;

            var sName = this._parent.getAttribute("data-name");

            var sUon = this.parentNode.getElementsByTagName("b")[0].innerHTML;

            var sTitle = this._parent.getElementsByTagName("label")[0].innerHTML;

            sUon = sUon == "-" ? "" : sUon;

            var inputs = this.parentNode.getElementsByTagName("input");

            var sMin = inputs[ 0 ].value;

            var sMax = inputs[ 1 ].value;

            if( self.Control.enterTips( this, sMin, sMax, inputs, self.toastr.warning ) ) return false;

            var condRange = self.Control.getCondRange( this, sMin, sMax, sUon );

            if( condRange.string ) templateConditonData["value"] = condRange.string;

            if( condRange.min || condRange.max ) conditionData = [ condRange.min, condRange.max ];

            self.setCondData( templateConditonData, conditionData, sName, sTitle, 1  );

        });


        // 快捷条件选择2
        self.$( self.Elems["condList2"]).delegate("button", "click", function( ev )
        {
            if( !self.$( this ).hasClass("btn-info") ) return false;

            var templateConditonData = {};

            var conditionData = [ "", ""];

            var inputs = this.parentNode.getElementsByTagName("input");

            this._parent = this._parent || this.parentNode.parentNode;

            var sName = this._parent.getAttribute("data-name");

            var sTitle = this._parent.getAttribute("data-title");

            var sUon = this.parentNode.getElementsByTagName("b")[0].innerHTML;

            sUon = sUon == "-" ? "" : sUon;

            var sMin = inputs[ 0 ].value;

            var sMax = inputs[ 1 ].value;

            if( self.Control.enterTips( this, sMin, sMax, inputs, self.toastr.warning ) ) return false;

            var condRange = self.Control.getCondRange( this, sMin, sMax, sUon );

            if( condRange.string ) templateConditonData["value"] = condRange.string;

            if( condRange.min || condRange.max ) conditionData = [ condRange.min, condRange.max ];

            self.setCondData( templateConditonData, conditionData, sName, sTitle, 1  );

            ev.stopPropagation();
        })
            .delegate( "input", "click", function()
            {
                if( this.type == "checkbox" )
                {
                    var templateConditonData = {};

                    var conditionData = [];

                    this._parent = this._parent || this.parentNode.parentNode.parentNode.parentNode;

                    var sTitle = this._parent.getAttribute("data-title");

                    var typeName = this.name;

                    var checkedInput = self.$("input:checked", this._parent );

                    for( var i = 0, f; f = checkedInput[ i ]; i += 1 )
                    {
                        var aValue = f.getAttribute("data-value");

                        var aName = f.getAttribute("data-name");

                        templateConditonData["value"] = templateConditonData["value"] || [];

                        templateConditonData["value"].push( aName );

                        conditionData.push( aValue || "" );
                    }

                    templateConditonData["value"] = templateConditonData["value"] ? templateConditonData["value"].join("，") : "";

                    self.setCondData( templateConditonData, conditionData, typeName, sTitle, 2  );
                }
            })
    },
    // 设置条件属性
    setCondData : function( templateConditonData, conditionData, sName, sTitle, sType )
    {
        this.Control.setCondDataItem( templateConditonData, conditionData, sName, sTitle, sType );

        var aa = this.Control.getTemplateConditionItem();

        this.printCondition( aa );

        this.searchHandle( sName ,conditionData );
    },

    contains:function( arr , ele ){
        for(var i in arr){
            if( arr[i] == ele){ return true; } }
        return false;
    },
    initPaint:function( templateConditonData, conditionData, sName, sTitle, sType ){

        this.Control.setCondDataItem( templateConditonData, conditionData, sName, sTitle, sType );

        var aa = this.Control.getTemplateConditionItem();

        this.printCondition( aa );
    },
    searchHandle : function( sName ,conditionData )
    {
        var can = ["QY","ZT"];

        //相互不能选择
        if( this.contains( can , sName  )){
            for(var i = 0 ; i< can.length ; i++){
                var tar = can[i];
                if( tar == sName ) continue;
                var cls = ".con-"+tar.toLowerCase();
                if( conditionData ){
                    conditionData !=0&&$( cls ).addClass("disabled");
                    conditionData==0&&$( cls ).removeClass("disabled");
                }else{
                    $( cls ).removeClass("disabled");
                }

            }
        }


    },
    search:function(){
        var self = this;

        var oSearchText = self.Elems["searchText"];

        var data = self.Control.getConditionItem();

        self.searchData( data , function(){
            self.$(self.chartBtn).click();
        });
    },
    // 条件层延迟处理
    reConditionConut : function()
    {
        var self = this;

        clearTimeout( self.contLayerTimer );

        self.contLayerTimer = setTimeout( function()
        {
            self.reCountHandle();

        }, 50 );
    },
    //初始化条件
    initCondition : function()
    {
        var oli = this.Elems["condList"].children;

        for( var i = 0, f; f = oli[ i ]; i += 1 )
        {
            if( f.tagName !== "LI" ) continue;

            if( f.children[ 1 ].tagName != "DIV" ) continue;

            var dropDown = document.createElement("a");

            dropDown.innerHTML = '展开 <i class="fa fa-angle-double-down"></i>';

            dropDown.style.display = "none";

            f.appendChild( dropDown );

            f._dropDown = dropDown;

            dropDown._li = f;

            dropDown.onclick = function()
            {
                if( this._status )
                {
                    this._li.style.height = this._height + "px";

                    this.innerHTML = '展开 <i class="fa fa-angle-double-down"></i>';

                    this._status = 0;
                }
                else
                {
                    this._height = this._height || this._li.offsetHeight - 1;

                    this._li.style.height = "auto";

                    this.innerHTML = '收起 <i class="fa fa-angle-double-up"></i>';

                    this._status = 1;
                }
            }
        }

    },

    reCountHandle : function()
    {
        var oli = this.Elems["condList"].children;

        for( var i = 0, f; f = oli[ i ]; i += 1 )
        {
            if( f.tagName !== "LI" ) continue;

            var oDiv = f.children[ 1 ];

            if( oDiv.tagName != "DIV" ) continue;

            var item = oDiv.children;

            var iWidth = 0;

            for( var n = 0, nf; nf = item[ n ]; n += 1 )
            {
                iWidth += this.$( nf ).outerWidth( true );
            }

            if( iWidth > oDiv.offsetWidth )
            {
                f._dropDown.style.display = "block";
            }
            else
            {
                f._dropDown.style.display = "none";
            }
        }
    },

    // 输出条件列表
    printCondition : function( tmplateCondtion )
    {
        var oElement = this.Control.printDataToTemplate( tmplateCondtion, this.Tmps["condtionList" ] );

        if( oElement.length )
        {
            this.Elems["condtionNull"].style.display = "none";
        }
        else
        {
            this.Elems["condtionNull"].style.display = "block";
        }

        this.$( this.Elems["condtionList"].getElementsByTagName("dd") ).remove();

        oElement.appendTo( this.$( this.Elems["condtionList"] ) )
    },
    // 根据条件输出筛选条件列表
    printConditionList : function()
    {
        var self = this;

        var conditionItem = this.Control.getConditionItem() || {};

        //console.log( conditionItem )

        this.$( "li", this.Elems["condList"] ).each( function()
        {
            var sName = this.getAttribute("data-name");
            var sStatus = this.getAttribute("data-status");
            var oData = conditionItem[ sName ];
            var $oA = null;

            if( oData )
            {
                self.$( "a", this ).removeClass("active");

                if( sStatus == 1 )
                {
                    var sV = oData.join("|");

                    var selectElement = self.$( "a[data-value='" + sV + "']", this );

                    if( selectElement[ 0 ] )
                    {
                        selectElement.addClass("active").siblings().removeClass("active");

                        selectElement.siblings("span").hide();
                    }
                    else
                    {
                        $oA = self.$( "a:eq( 0 )", this );

                        if( oData[ 0 ] && oData[ 1 ] )
                        {
                            self.$( "a[data-value='custom']", this ).addClass("active").siblings().removeClass("active");

                            var $span = $oA.siblings("span");

                            $span.show();

                            var inputs = $span.find( "input" );

                            inputs[ 0 ].value = oData[ 0 ];

                            inputs[ 1 ].value = oData[ 1 ];
                        }
                        else
                        {
                            $oA.addClass("active").siblings().removeClass("active");

                            $oA.siblings("span").hide();
                        }
                    }
                }
                else if( sStatus == 2 )
                {
                    for( var i = 0, f; f = oData[ i ]; i += 1 )
                    {
                        self.$( "a[data-value='" + f + "']", this ).addClass("active");
                    }
                }
            }
            else
            {
                $oA = self.$( "a:eq( 0 )", this );

                $oA.addClass("active").siblings().removeClass("active");

                $oA.siblings("span").hide();


            }
        });

        self.$( "input:text", self.Elems["condList2"]).each( function()
        {
            this.value = "";

            if( this.name == "max" )
            {
                var sName = this.parentNode.parentNode.getAttribute("data-name");

                var oData = conditionItem[ sName ];

                if( oData )
                {
                    self.$( this).siblings("input")[ 0 ].value = oData[ 0 ];

                    this.value = oData[ 1 ];
                }
            }
        });

        self.$( "ul.div_select", self.Elems["condList2"]).each( function()
        {
            var sName = this.parentNode.getAttribute("data-name");

            var oData = conditionItem[ sName ];

            self.$( "input:checkbox", this ).each( function()
            {
                this.checked = false;
            });

            if( oData )
            {
                for( var i = 0, f; f = oData[ i ]; i += 1 )
                {
                    self.$( "input:checkbox[data-value='"+ f +"']", this )[ 0 ].checked = true;
                }
            }
        });

    }
}